from luma.core.interface.serial import i2c
from luma.oled.device import ssd1306
from PIL import Image, ImageDraw, ImageFont
import time
from smbus2 import SMBus, i2c_msg

# AM2322传感器地址
AM2322_ADDRESS = 0x5C

# 初始化OLED (I2C地址通常是0x3C或0x3D)
serial = i2c(port=1, address=0x3C)
device = ssd1306(serial)

def read_am2322():
    try:
        with SMBus(1) as bus:
            # 唤醒传感器
            bus.write_byte(AM2322_ADDRESS, 0x00)
            time.sleep(0.001)
            
            # 发送读取命令
            write = i2c_msg.write(AM2322_ADDRESS, [0x03, 0x00, 0x04])
            read = i2c_msg.read(AM2322_ADDRESS, 8)
            bus.i2c_rdwr(write)
            time.sleep(0.0016)
            bus.i2c_rdwr(read)
            
            data = list(read)
            if len(data) < 8:
                return (None, None)
                
            # 数据处理(保持原来的CRC校验代码)
            humidity = ((data[2] << 8) | data[3]) / 10.0
            temperature = ((data[4] << 8) | data[5]) / 10.0
            return (temperature, humidity)
            
    except Exception as e:
        print("Error reading sensor:", e)
        return (None, None)

def display_data(temp, humi):
    # 创建新图像
    image = Image.new("1", (device.width, device.height))
    draw = ImageDraw.Draw(image)
    font = ImageFont.load_default()
    
    # 清屏并显示数据
    draw.rectangle((0, 0, device.width, device.height), outline=0, fill=0)
    draw.text((0, 0), "环境监测", font=font, fill=255)
    
    if temp is not None:
        draw.text((0, 15), f"温度: {temp:.1f} °C", font=font, fill=255)
    else:
        draw.text((0, 15), "温度: --.- °C", font=font, fill=255)
    
    if humi is not None:
        draw.text((0, 30), f"湿度: {humi:.1f} %", font=font, fill=255)
    else:
        draw.text((0, 30), "湿度: --.- %", font=font, fill=255)
    
    device.display(image)

# 主循环
while True:
    temp, humi = read_am2322()
    display_data(temp, humi)
    time.sleep(2)